package com.example.ccmusic

import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.util.Log
import androidx.appcompat.widget.AppCompatImageView

private const val TAG = "CircleImageView"

class CircleImageView(context: Context, attributeSet: AttributeSet) :
    AppCompatImageView(context, attributeSet) {

    private val paint = Paint()
    private val myMatrix: Matrix = Matrix()
    private var shader: BitmapShader? = null

    /**
     * 需要在设置宽高的时候设为正方形
     */
    override fun onDraw(canvas: Canvas?) {
        Log.d(TAG, "onDraw")
        if (drawable is BitmapDrawable && shader != null) {
            val radius = (measuredHeight / 2).toFloat()
            val bitmap = (drawable as BitmapDrawable).bitmap
            val scale = radius * 2 / bitmap.height.coerceAtMost(bitmap.width)
            Log.d(TAG, "onDraw: scale = $scale")
            myMatrix.reset()
            myMatrix.setScale(scale, scale)
            shader?.setLocalMatrix(myMatrix)
            paint.reset()
            paint.isAntiAlias = true
            paint.shader = shader
            canvas?.drawCircle(radius, radius, radius, paint)
        } else {
            super.onDraw(canvas)
        }
    }

    /**
     * 可以拓展一下吗，不仅仅是bitmap
     * 最后一步是不是都调用的setImageResource()?
     */
    override fun setImageBitmap(bm: Bitmap) {
        super.setImageBitmap(bm)
        shader = BitmapShader(bm, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
    }

}